<template>
	<view class="nav-header-box fix-top">
		<view @click="back()" class="back-icon">
			<uv-icon color="#999" name="arrow-left" size="22"></uv-icon>
		</view>
		<view class="title">
			用户登录
		</view>
		<view class="right">
			<uv-icon color="#999" name="home" size="22"></uv-icon>
		</view>
	</view>

	<view class="login form-box">
		<view class="logo">
			<uv-image width="350rpx" height="350rpx" alt="" src="/static/img/logo.png"></uv-image>
		</view>
		<uv-tabs :scrollable="false" class="form-tabs" :list="loginTypeList" @click="selectLoginType"></uv-tabs>
		<uv-form labelPosition="left" :rules="rules" :model="loginModel" ref="formLogin">
			<view class="form-item" v-if="loginType=='手机登录'">
				<uv-form-item prop="phone.mobile">
					<uv-input v-model="loginModel.phone.mobile" prefixIcon="phone" maxlength="11"
						placeholder="请输入常用手机号码" type="number">
					</uv-input>
				</uv-form-item>
				<uv-form-item prop="phone.mobileCode">
					<uv-input v-model="loginModel.phone.mobileCode" prefixIcon="empty-permission" maxlength="4"
						placeholder="请输入验证码">
						<!-- vue3模式下必须使用v-slot:suffix -->
						<template v-slot:suffix>
							<uv-code uniqueKey="page-login" keepRunning="true" ref="uCode" @change="codeChange"
								seconds="60" changeText="X秒后重新获取"></uv-code>
							<uv-button :disabled="uCodeDisabled" @click="getCode" :text="tips" type="success"
								size="mini"></uv-button>
						</template>
					</uv-input>
				</uv-form-item>
			</view>
			<view class="form-item" v-else-if="loginType=='密码登录'">
				<uv-form-item prop="password.username">
					<uv-input v-model="loginModel.password.username" placeholder="请输入用户名" type="number">
					</uv-input>
				</uv-form-item>
				<uv-form-item prop="password.password">
					<uv-input v-model="loginModel.password.password" placeholder="请输入密码" type="password">
					</uv-input>
				</uv-form-item>
			</view>
		</uv-form>
	</view>

	<view class="login-btn">
		<uv-button @click="submit()" customStyle="width:80%" shape="circle" type="primary" text="立即登录/注册"></uv-button>
	</view>
	<view class="login-btn" style="margin-top: 0.5rem;" v-if="isWechat">
		<uv-button @click="getOpenid()" customStyle="width:80%" shape="circle" type="success"
			text="授权进行微信登录"></uv-button>
	</view>

	<view>
		<p style="text-align: center">
			登录/注册即表示同意安安游 <br>
			<span @click="gotoUrl('')" style="color: royalblue;">《用户服务协议和隐私政策》</span>
		</p>
	</view>
</template>

<script>
	import {
		API_BASE_URL
	} from '@/common/public.js'
	import {
		isWeChatBrowser
	} from '@/common/public.js'

	export default {
		data() {
			return {
				appId: '你的微信公众号AppID',
				code: '',
				userToken: '',
				captcha: '',
				title: 'Hello',
				autoplay: true,
				duration: 500,
				indicatorDots: true,
				lazyLoad: true,
				value: 0,
				timeData: {},
				loginTypeList: [{
					name: '手机登录'
				}, {
					name: '密码登录'
				}],
				loginType: '手机登录',
				isWechat: true,
				tips: '',
				seconds: 60,
				loginModel: {
					phone: {
						mobile: '',
						mobileCode: '',
					},
					password: {
						username: '',
						password: '',
					},
				},
				uCodeDisabled: false
			}
		},
		onLoad() {
			// 检查URL中是否携带code参数（H5公众号授权回调）
			if (window.location.href.indexOf('code=') > -1) {
				this.handleAuthCallback()
			}
			this.isWechat = isWeChatBrowser()
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			gotoUrl(url) {
				uni.navigateTo({
					url: url
				})
			},
			selectLoginType(item) {
				this.loginType = item.name;
			},
			// 静默授权获取openid（snsapi_base）
			silentAuth() {
				// ifdef H5
				const redirectUri = encodeURIComponent(window.location.href)
				const authUrl =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
				window.location.href = authUrl
				// endif

				// ifdef MP-WEIXIN
				uni.login({
					provider: 'weixin',
					success: (res) => {
						this.code = res.code
						this.getOpenid()
					}
				})
				// endif
			},

			// 处理H5授权回调
			handleAuthCallback() {
				const url = window.location.href
				const code = url.split('code=')[1].split('&')[0]
				this.code = code
				this.getOpenid()
			},

			// 获取openid
			getOpenid() {
				uni.request({
					url: API_BASE_URL + '你的后端接口地址',
					method: 'POST',
					data: {
						code: this.code
					},
					success: (res) => {
						this.openid = res.data.openid
						uni.showToast({
							title: 'openid获取成功'
						})
					}
				})
			},

			// 用户主动授权获取详细信息（snsapi_userinfo）
			getUserInfo(e) {
				if (e.detail.errMsg === 'getUserInfo:ok') {
					const userInfo = e.detail.userInfo
					uni.request({
						url: API_BASE_URL + '',
						method: 'POST',
						data: {
							openid: this.openid,
							userInfo: userInfo
						},
						success: (res) => {
							uni.setStorageSync('userInfo', userInfo)
							uni.showToast({
								title: '授权成功'
							})
						}
					})
				}
			},

			codeChange(text) {
				this.tips = text;
			},

			getCode() {
				if (this.$refs.uCode.canGetCode) {
					// 向后端请求验证码
					uni.request({
						url: API_BASE_URL + '你的后端接口地址',
						method: 'GET',
						success: (res) => {
							this.captcha = res.data.openid
						}
					})
					this.uCodeDisabled = true
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							duration: 1500,
							title: '验证码已发送',
							icon: 'none'
						})
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}, 2000);
				} else {
					// 倒计时结束后再次向后端请求验证码
					uni.request({
						url: API_BASE_URL + '你的后端接口地址',
						method: 'GET',
						success: (res) => {
							this.captcha = res.data.openid
						}
					})
					this.uCodeDisabled = true
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							duration: 1500,
							title: '验证码已发送',
							icon: 'none'
						})
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}, 2000);
				}
			},

			submit() {
				let that = this;
				uni.request({
					url: API_BASE_URL + 'user.user/login',
					data: {
						phone: that.loginModel.phone,
						password: that.loginModel.password,
						loginMode: that.loginType === '手机登录' ? 'mobile' : 'password',
					},
					method: 'POST',

					success: (res) => {
						that.userToken = res.data.token
						if (res.data.token + '' !== '' && res.data.token !== null && res.data.token !== undefined) {
							// 保存用户登录状态token在本地
							uni.setStorageSync('loginToken', res.data.token);
							uni.showToast({
								icon: 'success',
								title: '登录成功',
								duration: 1000,
								mask: true
							})
							uni.navigateTo({
								url: '/pages/home/index'
							})
						} else {
							uni.showToast({
								icon: 'error',
								title: '登录失败，请稍后重试',
								duration: 1000,
								mask: true
							})
							// 2秒后清空输入框内容
							setTimeout(() => {
								that.loginModel.password.username = ''
								that.loginModel.password.password = ''
								that.loginModel.phone.mobileCode = ''
							}, 1200)
						}
					}
				})
			}
		}
	}
</script>

<style>
	.fix-top {
		position: fixed;
		width: 100%;
		background: #fff;
		top: 0;
		left: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 2rem;
	}

	.fix-top .nav-header-box {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		width: 100%;
		-webkit-box-pack: justify;
		-ms-flex-pack: justify;
		justify-content: space-between;
		height: 84rpx;
	}

	.fix-top .back-icon,
	.fix-top .right {
		width: 10%;
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;
		-webkit-box-pack: center;
		-ms-flex-pack: center;
		justify-content: center;
	}

	.fix-top .title {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;
	}

	.fix-top .title p {
		font-size: 1.1rem;
	}

	.fix-top .title span {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;
		margin-left: .3rem;
	}

	.fix-top .title img {
		display: block;
		width: 1.2rem;
		margin: 0 .3rem;
	}

	.form-box {
		padding-top: 44px;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.form-item {
		border-radius: .5rem;
		margin-bottom: 1.3rem;
		height: 8rem;
		width: 100%;
		box-sizing: border-box;
		padding: 0 2rem;
		line-height: 3rem;
	}

	.get-code {
		-webkit-transform: scale(0.5);
		transform: scale(0.5);
		font-size: 1.5rem;
		display: inline-block;
		width: 200%;
		margin-left: -50%;
	}

	.login-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
</style>